#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>


#define MSGNAME  "./msg_file"
    int msgid;
void my_exit(int sig)
{
    msgctl(msgid,IPC_RMID,NULL);
}

struct msgbuf
{
    long mtype;
    char mtext[1024];
};

int main()
{
    key_t key;

    pid_t pid;

    key = ftok(MSGNAME,'k');
    msgid = msgget(key,0644 | IPC_CREAT);
    if(msgid < 0)
    {
        perror("msgget error!");
        exit(1);
    }
    printf("key = %x\n",key);
    printf("msgid = %d\n",msgid);

    signal(SIGINT,my_exit);

    pid = fork();

    if(pid < 0)
    {
        perror("fork error!");
        exit(1);
    }
    else if(pid == 0)
    {
        char buffer[1024];
        long mtype;
        struct msgbuf pmsgbuf;

        while(1)
        {
            memset(buffer,0,sizeof(buffer));
            memset(&pmsgbuf,0,sizeof(pmsgbuf));
            printf("please input msg text:\n");
            scanf("%s",buffer);
            strcpy(pmsgbuf.mtext,buffer);
            printf("please input msg id:\n");
            scanf("%ld",&mtype);
            pmsgbuf.mtype = mtype;

            if(msgsnd(msgid,(void *)&pmsgbuf,sizeof(pmsgbuf),IPC_NOWAIT) < 0)
            {
                perror("msgsnd error!");
                exit(1);
            }
        }
    }
    else
    {
        char buffer[1024];
        long mtype;
        struct msgbuf pmsgbuf;
        size_t size;

        while(1)
        {
            memset(buffer,0,sizeof(buffer));
            memset(&pmsgbuf,0,sizeof(pmsgbuf));

            size = msgrcv(msgid,(void *)&pmsgbuf,sizeof(pmsgbuf),3,0);
            if(size < 0)
            {
                perror("msgrec error!");
                exit(1);
            }
            printf("rec data :%s\n",pmsgbuf.mtext);

            sleep(1);
        }
    }

    
    return 0;
}